<template>
  <view class="head" style="background-color: #ffcc00; height: 180rpx; display: flex; position: fixed; top: 0; left: 0; right: 0; z-index: 999;">
    <view style="height: fit-content; margin-top: 15%; margin-left: 35%; font-size: 32rpx;">客户端-预约</view>
  </view>
  <scroll-view class="page-container" scroll-y="true">
    <view class="calendar-content" v-if="showCalendar">
      <view class="calen">
        <uni-calendar 
          class="custom-calendar" 
          :selected="selectedDates" 
          :showMonth="false"
          @change="handleDateChange"
          :dateCellContent="dateCellContent"
        />
      </view>
    </view>

    <view class="nav-items-container">
      <view class="nav-item" v-for="(item, index) in filteredAppointments" :key="index">
        <text class="thing">{{ item.serviceName }}</text>
        <text class="time">{{ item.startTime }} - {{ item.endTime }}</text>
      </view>
    </view>

    <view v-if="filteredAppointments.length === 0 && selectedDate" class="no-appointment-tip">
      <text>当前日期没有预约记录</text>
    </view>

    <view v-if="showAuthModal" class="auth-modal">
      <view class="auth-modal-content">
        <view class="auth-modal-header">
          <text class="auth-modal-title">提示</text>
        </view>
        <view class="auth-modal-body">
          <text class="auth-modal-text">您还未登录，请先授权获取手机号</text>
        </view>
        <view class="auth-modal-footer">
          <button 
            class="auth-modal-button auth-modal-button-cancel"
            @click="showAuthModal = false"
          >
            取消
          </button>
          <button 
            class="auth-modal-button auth-modal-button-confirm"
            open-type="getPhoneNumber"
            @getphonenumber="handleGetPhoneNumber"
          >
            授权登录
          </button>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script>
import { getUserAppointmentRecord } from '@/api/wxlogin/wxlogin'
import { ref } from 'vue';
import { wxLogin } from '@/api/wxlogin/wxlogin';
import { getCustomerOrderList } from '@/api/system/login';
import { getOpenId} from '@/api/wxlogin/wxlogin';

export default {
  data() {
    return {
      showCalendar: true,
      selectedDates: [],
      appointments: [], // 所有预约数据
      filteredAppointments: [], // 当前显示的预约数据
      userId: uni.getStorageSync('userId'),
      selectedDate: null, // 新增当前选中日期
      showAuthModal: ref(false),
      isLoggedIn: ref(uni.getStorageSync('isLoggedIn') || false),
      phoneNumber: uni.getStorageSync('phoneNumber') || '',
      userInfo: uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : {}
    };
  },
  
  async created() {
    // 检查微信登录状态
    if (!this.checkLogin()) {
      return;
    }
    // 如果已登录，获取预约数据
    await this.fetchAppointments();
    await this.fetchCustomerOrders(); // 界面加载时调用

    // 设置当前日期为默认选中日期
    const currentDate = new Date().toISOString().split('T')[0];
    this.selectedDate = currentDate;
    this.handleDateChange({ fulldate: currentDate });
  },

  methods: {
    // 自定义日历单元格内容
    dateCellContent({ date, isSelected }) {
      const hasAppointment = this.selectedDates.some(item => item.date === date);
      if (hasAppointment) {
        return {
          top: '有预约',
          topStyle: {
            color: '#ff0000',
            fontSize: '12px'
          }
        };
      }
      return null;
    },

    // 检查微信登录状态
    checkLogin() {
      if (!this.isLoggedIn) {
        this.showAuthModal = true;
        return false;
      }
      return true;
    },

    async fetchAppointments() {
      try {
        const res = await getUserAppointmentRecord(this.userId);
        if (res.code === 200) {
          // 获取当前日期，并将时间部分设置为0
          const currentDate = new Date().toISOString().split('T')[0];
          
          // 过滤掉早于当前日期的预约
          const validAppointments = res.data.filter(item => {
            const appointmentDate = new Date(item.appointmentDate).toISOString().split('T')[0];
            return appointmentDate >= currentDate;
          });
          
          // 转换 selectedDates 为 uni-calendar 需要的格式
          this.selectedDates = validAppointments.map(item => ({
            date: item.appointmentDate,
            info: '有预约',
            data: {
              serviceName: item.serviceName
            }
          }));
          
          this.appointments = validAppointments;
          // 默认显示所有有效预约
          this.filteredAppointments = [...this.appointments];
        }
      } catch (err) {
        console.error('获取预约记录失败:', err);
      }
    },

    handleDateChange(e) {
      this.selectedDate = e.fulldate;
      if (this.selectedDate) {
        this.filteredAppointments = this.appointments.filter(item => 
          item.appointmentDate === this.selectedDate
        );
      } else {
        this.filteredAppointments = [...this.appointments];
      }
    },

    formatTime(date) {
      const d = new Date(date);
      // 显示日期和具体时间
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
    },

    handleConfirm() {
      if (!this.checkLogin()) {
        return;
      }
      // 已登录的逻辑
    },

    // 修改登录方法
    async wxLoginHandler() {
      console.log('开始获取登录code...');
      try {
        const loginRes = await new Promise((resolve, reject) => {
          wx.login({
            success: (res) => {
              if (res.code) {
                console.log('登录成功，code:', res.code);
                console.log('code类型:', typeof res.code);
                resolve(res.code);
              } else {
                console.error('获取code失败');
                reject(new Error('登录失败'));
              }
            },
            fail: (err) => {
              console.error('wx.login调用失败:', err);
              reject(err);
            }
          });
        });

        // 获取 openid
        const openIdRes = await getOpenId(loginRes);
        console.log('获取openid成功:', openIdRes);
        
        // 存储 openid
        if(openIdRes.code === 200) {
          uni.setStorageSync('openid', openIdRes.data.openid);
        }

        return loginRes;
      } catch(err) {
        console.error('登录过程失败:', err);
        throw err;
      }
    },

    // 手机号获取方法中也添加日志
    async handleGetPhoneNumber(e) {
      if (e.detail.errMsg !== 'getPhoneNumber:ok') {
        console.error('获取手机号失败:', e.detail.errMsg);
        uni.showToast({
          title: '获取手机号失败',
          icon: 'none'
        });
        return;
      }

      try {
        console.log('开始获取登录code...');
        const loginCode = await this.wxLoginHandler();
        console.log('获取到登录code:', loginCode);
        
        console.log('开始获取手机号...');
        console.log('手机号code:', e.detail.code);
        
        // 调用登录接口
        const res = await wxLogin({ 
          code: e.detail.code,
          loginCode: loginCode
        });
        console.log('登录接口返回:', res);

        if (res.code === 200) {
          uni.setStorageSync('isLoggedIn', true);
          uni.setStorageSync('userId', res.data.userId);
          uni.setStorageSync('phoneNumber', res.data.phoneNumber);
          uni.setStorageSync('userInfo', JSON.stringify({
            name: res.data.name,
            gender: res.data.gender,
            age: res.data.age,
            birthday: res.data.birthday,
            phoneNumber: res.data.phoneNumber
          }));
          
          this.showAuthModal = false;
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          });

          // 获取客户订单列表
          const orderRes = await getCustomerOrderList({ patientContact: res.data.phoneNumber });
          if (orderRes.code === 200) {
            this.processOrderDates(orderRes.data.list);
          }

          // 设置当前日期为默认选中日期
          const currentDate = new Date().toISOString().split('T')[0];
          this.selectedDate = currentDate;
          this.handleDateChange({ fulldate: currentDate });
        }
      } catch (err) {
        console.error('登录失败:', err);
        uni.showToast({
          title: err.message || '登录失败',
          icon: 'none'
        });
      }
    },

    // 处理订单日期
    processOrderDates(orderList) {
      this.appointments = [];
      this.selectedDates = [];

      const currentDate = new Date().toISOString().split('T')[0]; // 获取当前日期

      orderList.forEach(order => {
        const startDate = new Date(order.appointmentStartDate);
        const endDate = new Date(order.appointmentEndDate);

        // 遍历从startDate到endDate的每一天
        for (let d = startDate; d <= endDate; d.setDate(d.getDate() + 1)) {
          const dateStr = d.toISOString().split('T')[0];
          
          // 只添加当前日期及之后的预约
          if (dateStr >= currentDate) {
            // 添加到appointments
            this.appointments.push({
              serviceName: order.serviceName,
              appointmentDate: dateStr,
              startTime: order.serviceStartTime,
              endTime: order.serviceEndTime
            });

            // 添加到selectedDates
            this.selectedDates.push({
              date: dateStr,
              info: '有预约',
              data: {
                serviceName: order.serviceName
              }
            });
          }
        }
      });

      // 去重selectedDates
      this.selectedDates = this.selectedDates.filter((item, index, self) =>
        index === self.findIndex(t => t.date === item.date)
      );
    },

    async fetchCustomerOrders() {
      try {
        const phoneNumber = uni.getStorageSync('phoneNumber');
        if (!phoneNumber) return;

        console.log('传入的 patientContact:', phoneNumber); // 打印传入的参数

        const orderRes = await getCustomerOrderList({ patientContact: phoneNumber });
        
        if (orderRes.code === 200) {
          this.processOrderDates(orderRes.data.list);
        }
      } catch (err) {
        console.error('获取客户订单失败:', err);
      }
    }
  }
};

</script>

<style lang="scss">
.custom-calendar {
  width: 100%;
  height: 29rpx;

  .uni-calendar__header,
  .uni-calendar__content {
    font-size: 36rpx !important;
  }

  .uni-calendar__weeks {
    padding: 5rpx !important;
  }

  .uni-calendar__week-day {
    width: 45px !important;
    height: 30px !important;
    line-height: 45px !important;
  }
}

.page-container {
  height: 100vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-top: 180rpx;
}

.calendar-content {
  padding: 20rpx;
}

.nav-items-container {
  padding: 20rpx;
}

.nav-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;

  .thing {
    font-size: 28rpx;
    color: #333;
  }

  .time {
    font-size: 24rpx;
    color: #666;
  }
}

.no-appointment-tip {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}

.auth-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;

  .auth-modal-content {
    width: 80%;
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;

    .auth-modal-header {
      padding: 32rpx;
      border-bottom: 1rpx solid #eee;

      .auth-modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }

    .auth-modal-body {
      padding: 32rpx;

      .auth-modal-text {
        font-size: 28rpx;
        color: #666;
      }
    }

    .auth-modal-footer {
      display: flex;
      border-top: 1rpx solid #eee;

      .auth-modal-button {
        flex: 1;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 28rpx;
        border-radius: 0;
        margin: 0;

        &-cancel {
          background-color: #f5f5f5;
          color: #333;
        }

        &-confirm {
          background-color: #ffcc00;
          color: #333;
        }
      }
    }
  }
}
</style>